import React, { useEffect, useState } from "react";
import Avatar from "@/components/avatar";
import { accountMemberType, accountType } from "@/types";
import { View, Text, Button } from "@tarojs/components";
import { MoneyFormat } from "@/utils/format";
import moment from "moment";
import OperateList from "@/components/operateList";
import Taro from "@tarojs/taro";
import { defaultAvatarUrl, ShowToast } from "@/utils";
import http from "@/request";
import user from "@/store/user";
import account from "@/store/account";
import "./index.scss"

const Members: React.FC<{
    members?: accountMemberType[],
    accountData?: accountType,
    onMemberEdit: (member: accountMemberType) => void
    onMemberDelete: (member: accountMemberType) => void
    onChange?: () => void
}> = ({ members, onMemberEdit, onMemberDelete, accountData, onChange }) => {

    const AccountItem: React.FC<{ item: accountMemberType }> = (props) => {
        const member = props as unknown as accountMemberType
        return <View className="member-item flex-row flex-item">
            <View className="member-info-container flex-row flex-item">
                <View className="user-name-container flex-column flex-item">
                    <Avatar url={member.avatarUrl} size="80rpx"></Avatar>
                    <View className="font-size24">{member.userName}</View>
                </View>
                <View className="account-content font-size28">
                    <View className="form-info-item flex-row flex-item">
                        <View className="form-info-item-label">初始资金：</View>
                        <View className="form-info-item-value">{MoneyFormat(member.initAmount)}</View>
                    </View>
                    <View className="form-info-item flex-row flex-item">
                        <View className="form-info-item-label">加入时间：</View>
                        <View className="form-info-item-value">{moment(member.createTime).format('YYYY-MM-DD HH:mm:ss')}</View>
                    </View>
                </View>
            </View>
            <View className="move-action flex-row">
                <View onClick={() => onMemberEdit(member)} className="flex1 flex-row flex-center active-btn">
                    <Text className="iconfont icon-base-edit2"></Text>
                    <Text>编辑</Text>
                </View>
                <View onClick={() => onMemberDelete(member)} className="flex1 flex-row flex-center active-btn">
                    <Text className="iconfont icon-base-del"></Text>
                    <Text>删除</Text>
                </View>
            </View>
        </View>
    }

    Taro.useShareAppMessage(_ => {
        return {
            title: `${user.info?.userName || '好友'}邀你加入账本：${accountData?.name}`,
            path: `/pages/accounts/accountDetail/index?accountid=${accountData?.id}&sharetime=${new Date().getTime()}`
        }
    })

    const [shareParams, setShareParams] = useState<{ sharetime?: number, accountid?: number }>({})

    const addMember = (accountId) => {
        if ((accountData?.members || []).some(item => {
            return item.userId === user.info?.id
        })) {
            return '已经添加'
        }
        http.post('/account-user/add', {
            userId: user.info?.id,
            accountId
        }).then(_ => {
            ShowToast("加入账本成功")
            user.updateInfo()
            account.doUpDateAccount()
        }).catch(err => {
            ShowToast(err.msg || '加入账本失败')
        }).finally(() => {
            onChange && onChange()
        })
    }

    useEffect(() => {
        const now = new Date().getTime()
        const { sharetime, accountid } = shareParams
        if (sharetime && accountid && accountData) {
            // 链接有效期1小时
            if ((now - sharetime < 60 * 60 * 1000)) {
                addMember(accountid)
            } else {
                ShowToast('邀请链接已过期！')
            }
        }
    }, [shareParams, accountData])

    Taro.useLoad(params => {
        const { sharetime, accountid } = params
        setShareParams({ sharetime, accountid })
    })

    return <View className="member-list-container">
        <OperateList
            noDataTitle="当前账本没有成员"
            noDataDesc="请点击下面按钮邀请"
            listData={(members || [])}
            childNode={AccountItem}>
        </OperateList>
        <View className="flex-row">
            <View onClick={() => onMemberEdit({
                avatarUrl: defaultAvatarUrl
            })} className="add-account-btn add-btn border-main-color flex-row flex-center">
                <Text className="iconfont font-size32 icon-base-add"></Text>
                <Text>创建成员</Text>
            </View>
            <View className="flex1"></View>
            <View className="add-account-btn invite-btn border-main-color flex-row flex-center">
                <Text className="iconfont font-size32 icon-weixin"></Text>
                <Text>邀请成员</Text>
                <Button className="share-btn" openType="share"></Button>
            </View>
        </View>
    </View>
}

export default Members